package com.hue.concurrent.day06;

/**
 * 使用volatile优化两阶段终止模式
 */
public class Demo03 {
    public static void main(String[] args) {
        TwoStop twoStop = new TwoStop();
        twoStop.start();
        twoStop.start();

        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        twoStop.stop();
    }

    public static class TwoStop {
        private Thread monitor;
        private volatile boolean flag = true;
        //判断监控线程是否正在执行,防止监控线程被多次启动
        private volatile boolean starting = false;

        /**
         * 启动一个监控线程
         */
        public void start() {
            synchronized (this) {
                if (starting) {
                    return;
                }
                starting = true;
            }
            monitor = new Thread(() -> {
                while (true) {
                    if (Thread.currentThread().isInterrupted() || !flag) {
                        System.out.println("处理后事...");
                        starting = false;
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName() + ":正常监控...");
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
            monitor.start();
        }

        public void stop() {
            flag = false;
            monitor.interrupt();
        }
    }
}

